var dialogs = new (function () {
	var currentDialog = [];
	var container;
	this.show = function (id) {
		var el = document.getElementById(id);
		if(currentDialog.length){
		currentDialog[currentDialog.length-1].style.display = "none";
		}
		el.style.display = "block";
		container.style.display = "block";
		currentDialog.push(el);
	};
	this.hide = function () {
		if(currentDialog.length){
			currentDialog.pop().style.display = "none";
		}
		if(currentDialog.length == 0)container.style.display = "none";
		else {
			currentDialog[currentDialog.length-1].style.display = "block";
		}
	};
	this.load = function () {
		container = document.getElementById("dialog-container");
	};
})();


var profiloBt = function(e){
	data.profilo(event.target.parentElement.id);
};


var data = new (function () {
	//CACHE risultati ricerca.
	var searchResults = {};
	var currData = null;
	var aiutoEmail, aiutoDest, aiutoAbilita;
	var selectedAbilita;
	var searchNome, searchCognome, searchCitta, searchEmail, searchAmici;
	var req = new XMLHttpRequest();
	req.onreadystatechange = function () {
			if (req.readyState != 4) return;
			if (req.status != 200 && req.status != 304) {
				alert('HTTP error ' + req.status);
				return;
			}else if (req.status == 200) {
				currData = JSON.parse(req.responseText); 
				var l = document.getElementById("results-list");
				var a  = currData.results;
				if(a.length){
				l.innerHTML = "";
				for(var u in a){
					u = a[u];
					searchResults["U"+ u.idUtente] = u;
					var el = document.createElement("li");
					el.innerHTML += "<label onclick='profiloBt(event)'>"+u.nome+" " + u.cognome +"</label>"+
					"<div class='descrizione'>"+ u.citta +"</div>";
					el.id="U"+ u.idUtente;
					if(!(u.idUtente in mieiAmici)){
						var b = document.createElement("a");
						b.className ="button ";
						b.textContent = "+ amico!";
						el.insertBefore(b, el.firstChild);
						b.onclick = addAmicoBt;
					}
					if(currData.abilita){
						var b = document.createElement("a");
						b.className ="button ";
						b.textContent = "Aiutami!";
						el.insertBefore(b, el.firstChild);
						b.onclick = aiutamiBt;
					}
					l.appendChild(el);
					
				}
				}else{
					l.innerHTML = "<li><div style='text-align:center' class='descrizione'>La ricerca non ha prodotto risultati.</div></li>";
				}
				dialogs.hide();
				dialogs.show('dialogo-risultati-cerca');
				return;
			}
			
	};
	var addAmicoBt = function() {
		var el = event.target;
		var id = searchResults[el.parentElement.id].idUtente;
		azione({"comando":"AMICIZIA","mode":"aggiungi", "id":id},
				function(response){
				if(! response.commit) return alert("Errore Interno");
				mieiAmici[id] = 1;
				el.parentElement.removeChild(el);
				});
	};
	this.fetch = function () {
		var ab = selectedAbilita.id;
		if(ab == "noAbilita-cerca") ab = "";
		else ab = ab.slice(1);
		var tmp = 
			"citta="+searchCitta.value
			+"&email="+searchEmail.value
			+"&cognome="+searchCognome.value
			+"&nome="+searchNome.value
			+"&amici="+(searchAmici.value == 1)
			+"&abilita="+ ab
			;
		req.open("POST","./cerca.jsp",true);
		req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");  
		req.send(tmp);
	};
	this.load = function() {
		aiutoDest = document.getElementById("dest-aiuto");
		aiutoEmail = document.getElementById("email-aiuto");
		aiutoAbilita = document.getElementById("abilita-aiuto");
		selectedAbilita = document.getElementById("noAbilita-cerca");
		searchNome = document.getElementById("search-nome");
		searchCognome =document.getElementById("search-cognome");
		searchCitta =document.getElementById("search-citta");
		searchEmail =document.getElementById("search-email");
		searchAmici = document.getElementById("search-amici");
	};
	this.profilo = function(id){
		infoUtente.fetch(searchResults[id].idUtente);
	};
	var aiutEl;
	var aiutamiBt = function(){ 
		aiutEl = event.target;
		var u = searchResults[aiutEl.parentElement.id];
		aiutoDest.textContent = u.nome;
		aiutoEmail.textContent = u.idUtente;
		aiutoAbilita.textContent = currData.abilita;
		document.getElementById("commento-aiuto").value = "";
		dialogs.show('dialogo-aiuto');
	};
	this.aiutoConfirm = function(){
		azione({"comando":"AIUTO",
			"abilita":currData.abilita,
			"id":aiutoEmail.textContent,
			"descrizione":document.getElementById("commento-aiuto").value
			},function(response){
				if(! response.commit) return alert("Errore Interno");
				aiutEl.parentElement.removeChild(aiutEl);
				dialogs.hide();
		});
	}
	this.selectAbilitaBt = function(e){
		var el = event.target;
		if(selectedAbilita == el) return;
		if(selectedAbilita) selectedAbilita.className = selectedAbilita.className.replace(" selected","");
		el.className += " selected";
		selectedAbilita = el;	
	}
})();


var infoUtente = new (function () {
	var req = new XMLHttpRequest();
	var feedbacksList, email, citta, nome, eta;
	req.onreadystatechange = function () {
			if (req.readyState != 4) return;
			if (req.status != 200 && req.status != 304) {
				alert('HTTP error ' + req.status);
				return;
			}else if (req.status == 200) {
				u = JSON.parse(req.responseText);
				email.textContent = u.idUtente;
				nome.textContent = u.nome + " " + u.cognome;
				var abs = Object.keys(u.abilita).join(", ");
				if(abs == "") abs = "Nessuna Abilità.";
				else abs = "Abilità dichiarate: " + abs;
				abilita.textContent = abs;
				
				citta.textContent = u.citta;
				eta.textContent =  ((new Date()).getFullYear() - new Date(u.eta).getFullYear());
				if(u.feedbacks.length){
				feedbacksList.innerHTML = "";
				for(var f in u.feedbacks){
					f = u.feedbacks[f];
					var el = document.createElement("li");
					
					var b = document.createElement("div");
					b.className ="auth";
					el.appendChild(b);
					
					var r = document.createElement("div");
					r.className ="rate";r.innerHTML = f.valore + "/5 stelle";
					b.appendChild(r);
					var d = document.createElement("div");
					d.className ="descrizione";
					d.textContent = d.autore + " - " + new Date(f.data).toDateString();
					b.appendChild(d);
					
					var c = document.createElement("div");
					c.className ="content"; c.textContent = f.commento;
					el.appendChild(c);
					
					feedbacksList.appendChild(el);
				}
				}else{
					feedbacksList.innerHTML = "<li><div style='text-align:center' class='descrizione'>Non ha ricevuto feedback.</div></li>";
				}
				dialogs.show('dialogo-profilo-utente');
				return;
			}
	};
	this.load = function () {
		container = document.getElementById("dialog-container");
		feedbacksList = document.getElementById("utente-feedback-list");
		email = document.getElementById("dialogo-profilo-utente-email");
		citta = document.getElementById("dialogo-profilo-utente-citta");
		nome = document.getElementById("dialogo-profilo-utente-nome");
		abilita = document.getElementById("dialogo-profilo-utente-abilita");
		eta = document.getElementById("dialogo-profilo-utente-eta");
		
	};
	this.fetch = function (id) {
		req.open("POST","./InfoUtente.jsp",true);
		req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");  
		req.send("idUtente="+id);
	};
})();

var profilo = new (function(){
	var mieAbilitaElenco, mieAbilitaList;
	var mieiDatiElenco;
	var cognome, citta, nascita, nome;

	var checkSave = function(obj, el, name){
		if(el.value != "" && el.value != mieiDati[name]) obj[name] = el.value;
	}
	var changedDati = function(response,obj){
		if(! response.commit){alert("Verificare i dati inseriti!"); return;}
		for(var name in obj) mieiDati[name] = obj[name];
		dialogs.hide();
	}
	this.save = function(){
		var obj = {"comando":"MODIFICA_profilo"};
		checkSave(obj, cognome, "cognome");
		checkSave(obj, nome, "nome");
		checkSave(obj, citta, "citta");
		//checkSave(obj, nascita, "nascita");
		
		azione(obj,function(response){
			changedDati(response,obj);
		});
		
		dialogs.hide();
		profilo.show();
	};
	this.changePassword = function(){
		document.getElementById("password-new").value = "";
		document.getElementById("password-new-2").value = "";
		document.getElementById("password-msg").textContent = "";
		dialogs.show('dialogo-password');
	}
	this.changePasswordConfirm = function(){
		var a = document.getElementById("password-new");
		var b = document.getElementById("password-new-2");
		var msg = document.getElementById("password-msg");
		
		var p = a.value;
		if(p == "") return msg.textContent = ("Inserire la nuova password.");
		var p2 = b.value;
		
		if(p == p2) azione({"comando":"MODIFICA_PASSWORD", "password":p},
			function(response){
			if(response.commit)alert("Password cambiata con successo.");
			else alert("Errore  cambiando la passowrd.");
			dialogs.hide();
			});
		else msg.textContent ="Le password non corrispondono.";
	}
	var selectedAbilita = null;
	var selectAddAb = function(){
		var el = event.target;
		if(selectedAbilita == el) return;
		if(selectedAbilita) selectedAbilita.className = selectedAbilita.className.replace(" selected","");
		el.className += " selected";
		selectedAbilita = el;
	}
	this.addAbilita = function(){
		
		selectedAbilita = null;
		var list = document.getElementById("add-ab-list");
		list.innerHTML = "";
		for(var a in abilitaValide){
			a = abilitaValide[a];
			if(a in mieAbilita)continue;
			
			list.appendChild(createAbilitaButton(a,selectAddAb,"addA-"));
		}
		
		dialogs.show('dialogo-add-ab');
	}
	
	this.addAbilitaConfirm = function(){
		var a = selectedAbilita.id.split("-")[1];
		azione({"comando":"ABILITA_PERSONALI","mode":"aggiungi", "nome":a},
				function(response){
					if(response.commit)mieAbilita[a] = 1;
					else alert("Errore aggiungendo l'abilità.");
					dialogs.hide();
					profilo.edit();
				});
	}
	var delAb = function(){
		var a = event.target.parentElement.id.split("-")[1];
		azione({"comando":"ABILITA_PERSONALI","mode":"rimuovi", "nome":a},
				function(response){
					if(response.commit)delete mieAbilita[a];
					else alert("Errore rimuovendo l'abilità.");
					dialogs.hide();
					profilo.edit();
				});
	}
	this.show = function(){
		mieiDatiElenco.innerHTML = 
			mieiDati.nome + " " +  mieiDati.cognome + " <br /> " +
			mieiDati.email + " - " +  mieiDati.citta + " - " + 
			((new Date()).getFullYear() - mieiDati.dataNascita.getFullYear()) + " anni";
		
		var abs = Object.keys(mieAbilita).join(", ");
		if(abs == "") abs = " nessuna";
		else abs = " " + abs;
		
		mieAbilitaElenco.innerText = abs;
		dialogs.show('dialogo-my-profilo');
	}
	this.edit = function(){
		mieAbilitaList.innerHTML = "<li><a style=\"width:80%; float:initial;\" onclick=\"profilo.addAbilita()\" class=\"button\">Aggiungi Abilita</a></li>";
		cognome.value = mieiDati.cognome;
		nome.value = mieiDati.nome;
		citta.value = mieiDati.citta;
		nascita.value = mieiDati.nascita;
		
		for(var a in mieAbilita){
			//a = mieAbilita[a];
			var el = document.createElement("li");
			el.id = "mieAb-"+a;
			el.textContent = a;
			var b = document.createElement("a");
			b.className ="button";
			b.textContent = "Elimina";
			b.onclick = delAb;
			el.appendChild(b);
			mieAbilitaList.appendChild(el);
		}
		dialogs.show('dialogo-my-profilo-edit');
	}
	this.load = function(){
		mieAbilitaElenco = document.getElementById("mieAbilitaElenco");

		mieAbilitaList = document.getElementById("mieAbilita-list");
		mieiDatiElenco = document.getElementById("mieiDatiElenco");
		
		cognome = document.getElementById("my-edit-cognome");
		nome = document.getElementById("my-edit-nome");
		citta = document.getElementById("my-edit-citta");
		nascita = document.getElementById("my-edit-nascita");
		

		

	}
})();

var gestoreabilita = new (function(){
	var id ="";
	this.proponi = function(){
		document.getElementById("proponi-ab-nome").value = "";
		dialogs.show("dialogo-proponi-ab");
	}
	this.proponiConferma = function(){
		azione({"comando":"PROPOSTA_ABILITA","id":document.getElementById("proponi-ab-nome").value},
			function(response){
			if(! response.commit) return alert("Errore Interno");
			dialogs.hide();
		});
	}
})();
var createAbilitaButton = function(nome, callback, ns){
	var el = document.createElement("li");
	el.id= ns + nome;
	el.style.backgroundColor = "hsl(" + ((nome.length*100 % 36)*10)+",83%,88%)";
	el.onclick = callback;
	el.textContent = nome;
	if (nome.length > 20) el.className = (" class=\"very-long\"");
	else if (nome.length > 10) el.className =(" class=\"long\"");
	return el;
}
var amici = new (function(){
	this.show = function(){
		req.open("POST","./amici.jsp",true);
		req.send();
	}
	this.load = function(){
		
	}
	var searchResults = {};
	var currData = null;
	
	var req = new XMLHttpRequest();
	req.onreadystatechange = function () {
			if (req.readyState != 4) return;
			if (req.status != 200 && req.status != 304) {
				alert('HTTP error ' + req.status);
				return;
			}else if (req.status == 200) {
				currData = JSON.parse(req.responseText); 
				var l = document.getElementById("lista-amici");
				var a  = currData.results;
				if(a.length){
				l.innerHTML = "";
				for(var u in a){
					u = a[u];
					searchResults["U"+ u.idUtente] = u;
					var el = document.createElement("li");
					el.innerHTML += "<label onclick='profiloBt(event)'>"+u.nome+" " + u.cognome +"</label>"+
					"<div class='descrizione'>"+ u.citta +"</div>";
					el.id="U"+ u.idUtente;
					var b = document.createElement("a");
					b.className ="button ";
					b.textContent = "Rimuovi";
					el.insertBefore(b, el.firstChild);
					b.onclick = delAmicoBt;
					
					l.appendChild(el);
					
				}
				}else{
					l.innerHTML = "<li><div style='text-align:center' class='descrizione'>Non hai amici!</div></li>";
				}
				dialogs.show('dialogo-amici');
				return;
			}
			
	};
	var delAmicoBt = function() {
		var el = event.target.parentElement;
		var id = searchResults[el.id].idUtente;
		azione({"comando":"AMICIZIA","mode":"rimuovi", "id":id},
				function(response){
				if(! response.commit) return alert("Errore Interno");
				delete mieiAmici[id];
				el.parentElement.removeChild(el);
				});
	};
	
	var lowProfilo = function(id){
		infoUtente.fetch(searchResults[id].idUtente);
	};
})();

var notifiche = new (function(){
	var el;
	var id;
	this.azione = function(e,a){
		el = e.target;
		tmp = el.parentElement.parentElement.id.split("@");
		var id = tmp[1];
		var tipo = tmp[0];
		azione({"comando":"NOTIFICA",
			"status":a,
			"tipo":tipo,
			"id":id},
			function(response){
			if(! response.commit) return alert("Errore Interno");
			if(a =="ACCETTATA" ) el.parentElement.innerHTML = "<b style=''>Hai accettato.</b>";
			else	el.parentElement.innerHTML = "<b style=''>Hai rifiutato.</b>";
			//el.parentElement.removeChild(el);
		});
	}
	this.feedback = function(e){
		el = e.target;
		id = el.parentElement.parentElement.id.split("@")[1];
		document.getElementById("feedback-commento").value = "";
		document.getElementById("feedback-rate").value = 3;
		dialogs.show('dialogo-feedback');
		
	}
	this.feedbackConfirm = function(){
		var commento = document.getElementById("feedback-commento").value;
		var rate = document.getElementById("feedback-rate").value;
		if(!commento) return alert("Scrivi un commento!");
		azione({"comando":"FEEDBACK",
			"commento":commento,
			"rate":rate,
			"id":id},
			function(response){
			if(! response.commit) return alert("Errore Interno");
			el.parentElement.innerHTML = "";
			dialogs.hide();
		});
	}
})();

var azione = function (params, callback){
	var str = [];
	for(var p in params) str.push(p + "="+ params[p]);
	str = str.join("&");

	var req = new XMLHttpRequest();
	req.onreadystatechange = function () {
			if (req.readyState != 4) return;
			if (req.status != 200 && req.status != 304) {
				alert('HTTP error ' + req.status);
				return;
			}else if (req.status == 200) {
				callback(JSON.parse(req.responseText));
				
			}
	};
	
	req.open("POST","../Azioni",true);
	req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");  
	req.send(str);
	
}


